/*  

2006-Mar-28 Jeremy

這是為了做類似 eclipse tab 上面有 close button 的效果
所以直接從 Button 下手，overlay 一個 sprite 去做為 hit-area
並且透過 layoutContents() 讓這個 hit-area sprite 永遠在最上層，才能trigger roll_over, mouseDown event


*/
package com.jy.travel.components {
	import mx.controls.*;
	import flash.display.*;
	import mx.styles.*
	import flash.events.MouseEvent;
	import flash.events.Event;;
	import mx.core.*
	import flash.text.TextLineMetrics;
	import flash.geom.Point;
	import mx.events.ItemClickEvent;
	

	use namespace mx_internal;

	public class MyButton extends Button {
		
		var s:Sprite
		
		public function MyButton(){
			
			super();
			
			//
			this.mouseChildren = true;
			this.addEventListener("creationComplete", onComplete);
			
			//create overlay hit-area - this sprite will always swap to top-most !
			s = new Sprite();
			s.graphics.beginFill(0xff0000, 0);
			s.graphics.drawRect(0, 0, 18, 18);
			s.name="mysprite";
			//s.addEventListener("rollOver", onHitSpriteOver );
			s.addEventListener("mouseDown", onHitSpriteDown );
			s.mouseEnabled = true;
			this.addChild(s);
		}
		
		//adjust hit-area size and position, to correctly overlay the icon
		private function onComplete(evt:Event){
			
			//trace(this.currentIcon.width);
			//要先檢查建立時是否有顯示icon - 有可能是在 不顯示 icon 的狀態新增 tab
			if(this.getStyle("icon") != null){
				s.width = this.currentIcon.width;
				s.height = this.currentIcon.height;
				s.x = this.currentIcon.x;
				s.y = this.currentIcon.y;
			}
		}
		
		//偵聽 roll_over 其實沒什麼意義，只是測試用
		public function onHitSpriteOver(evt:Event){
			//trace("onUOver");
		}
		
		//真正重要的是 mouseDown時要廣播，外界才知道要接手做後續處理 - 例如移除這個tab
		public function onHitSpriteDown(evt:Event){
			//trace("onUDown");
			
			//when hitSprite clicked, eat the event so it won't bubble and 
			//parent (Tab) will not recevie tab click event.
			evt.stopImmediatePropagation();
			
			this.dispatchEvent( new ItemClickEvent("buttonClose", true, true) );
		}
		
		//swap the hit-sprite to top so it can trigger rollOver and mouseDown event
		//note it's overrideing public instead of mx_internal - weird but works
		override mx_internal function layoutContents(unscaledWidth:Number,unscaledHeight:Number, offset:Boolean):void{
	    	super.layoutContents(unscaledWidth, unscaledHeight, offset);
	    	this.setChildIndex(this.getChildByName("mysprite") , this.numChildren-1);
	    }
	
	
	}
}